package org.thirdHero.admin.web;

import com.alibaba.druid.util.StringUtils;
import org.thirdHero.admin.annotation.LoginAdmin;
import org.thirdHero.core.util.ResponseUtil;
import org.thirdHero.db.domain.SysDept;
import org.thirdHero.db.domain.SysUser;
import org.thirdHero.db.service.SysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/admin/dept")
public class SysDeptController {
    private static final Logger logger = LoggerFactory.getLogger(SysDeptController.class);
    @Resource
    SysDeptService sysDeptService;
    @GetMapping("/list")
    public Object list(@LoginAdmin SysUser sysUser , String simplename,
                       @RequestParam(value = "page",defaultValue = "1")Integer page,
                       @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                       String sort, String order){
        List<SysDept> sysDepts = sysDeptService.querySelective(simplename, page, limit, sort, order);
        int total = sysDeptService.countSelective(simplename,page,limit,sort,order);
        ResponseUtil<SysDept> responseUtil = new ResponseUtil<SysDept>();
        return  responseUtil.ok("成功",total, sysDepts);
    }
    @PostMapping("/create")
    @ResponseBody
    public Object addDept(@LoginAdmin SysUser sysUser ,@RequestBody SysDept sysDept){
        SysDept deptBySimpleName = this.sysDeptService.findDeptBySimpleName(sysDept.getSimplename());
        if(deptBySimpleName!=null){
            return ResponseUtil.errorBussiness("该部门已存在");
        }else{
            deptSetPid(sysDept);
            this.sysDeptService.insertLiteMallDept(sysDept);
            return ResponseUtil.ok("保存成功！");
        }
    }
    @GetMapping("/findByPid/{pid}")
    @ResponseBody
    public Object findByPid(@LoginAdmin SysUser sysUser ,@PathVariable String pid){
        List<SysDept> deptChild = this.sysDeptService.findLiteMallDeptByPid(Integer.parseInt(pid));
        if(deptChild!=null && !deptChild.isEmpty()){
            return ResponseUtil.ok(deptChild.get(0));
        }else{
            return ResponseUtil.fail(-1,"没有该节点信息");
        }
    }
    @PutMapping("/editDept/{id}")
    @ResponseBody
    public Object editDept(@LoginAdmin SysUser sysUser , @RequestBody SysDept sysDept, @PathVariable String id){
        SysDept dept = this.sysDeptService.findLIteMallDeptById(Integer.parseInt(id));
        if (dept != null) {
            SysDept deptBySimpleName = this.sysDeptService.findDeptBySimpleName(sysDept.getSimplename());
            if(!sysDept.getSimplename().equals(dept.getSimplename())){
                if(deptBySimpleName!=null ){
                    return ResponseUtil.errorBussiness("该部门已存在");
                }
            }
            sysDept.setId(dept.getId());
            deptSetPid(sysDept);
            if(sysDept.getId().equals(sysDept.getPid())){
                return ResponseUtil.fail(-1,"不能将自己添加为父节点");
            }
            int result = this.sysDeptService.updateLIteDeptByid(sysDept);
            if(result == 1){
                return ResponseUtil.ok("更新成功");
            }else{
                return ResponseUtil.fail(-1,"更新失败请重试");
            }
        }else{
            return ResponseUtil.fail(-1,"没有找到要修改的部门信息");
        }
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Object deleteDelete(@LoginAdmin SysUser sysUser ,@PathVariable String id){
        SysDept dept = this.sysDeptService.findLIteMallDeptById(Integer.parseInt(id));
        if(dept!=null){
            List<SysDept> deptChilds = this.sysDeptService.findLiteMallDeptByPid(Integer.parseInt(id));
            if(deptChilds!=null && !deptChilds.isEmpty()){
                return ResponseUtil.fail(-1,"该部门下有子部门，请删除所有子部门后重试！");
            }else{
                int result = this.sysDeptService.deleteDeptById(Integer.parseInt(id));
                if(result == 1){
                    return ResponseUtil.ok("删除成功");
                }else{
                    return ResponseUtil.fail(-1,"删除失败请重试");
                }
            }
        }else{
            return ResponseUtil.fail(-1,"该部门不存在无法删除");
        }
    }

    @GetMapping("/queryDeptTree")
    public Object queryDeptTree(@RequestParam(required = false)String simpleName){
        List<SysDept> depts;
        if(StringUtils.isEmpty(simpleName) || "".equals(simpleName)){
            depts = this.sysDeptService.findLiteMallDeptByPid(0);
        }else{
            depts = this.sysDeptService.queryLiteMallDeptBySimpleName(simpleName);
        }
        if(depts!=null && !depts.isEmpty()){
            for( SysDept sysDept : depts){
                getChild(sysDept);
            }
        }
        ResponseUtil<SysDept> response = new ResponseUtil<SysDept>();
        return response.ok("成功",depts!=null?depts.size():0,depts);
    }
    public List<SysDept> getChild(SysDept sysDept){
        List<SysDept> sysDepts = sysDeptService.findLiteMallDeptByPid(sysDept.getId());
        if(sysDepts !=null && !sysDepts.isEmpty()){
            sysDept.getChildren().addAll(sysDepts);
        }else{
            sysDept.setChildren(null);
        }
        if (sysDepts != null) {
            sysDepts.forEach(this::getChild);
        }
        if(sysDepts.size()==0){
            return null;
        }
        return sysDepts;
    }
    private void deptSetPid(SysDept dept){
        if(dept==null || dept.getPid()==null || dept.getPid()==null){
            dept.setPid(0);
            dept.setPids("[0],");
            dept.setLevel(1);
        }else{
            SysDept sysDept = this.sysDeptService.findLIteMallDeptById(dept.getPid());
            if(sysDept !=null){
                dept.setPid(sysDept.getId());
                dept.setLevel(sysDept.getLevel()+1);
                dept.setPids(sysDept.getPids() + "[" + sysDept.getId() + "],");
            }
        }
    }
}
